<?php

namespace app\admin\service;

use app\model\User;
use app\model\UserBlack;
use think\facade\Db;

class BlackService
{
	private $userModel;
	private $userBlackModel;

	public function __construct(User $userModel, UserBlack $userBlackModel)
	{
		$this->userModel = $userModel;
		$this->userBlackModel = $userBlackModel;
	}

	public function getUserBlackList(array $params)
	{
		$uid = (int)$params['uid'];
		$phone = (string)$params['phone'];
		$page = (int)$params['page'];
		$limit = (int)$params['limit'];
		$startDate = (string)$params['start_date'] ? date('Y-m-d 00:00:00', strtotime($params['start_date'])) : date('Y-m-d 00:00:00');
		$endDate = (string)$params['end_date'] ? date('Y-m-d 23:59:59', strtotime($params['end_date'])) : date('Y-m-d 23:59:59');

		$data = $this->userBlackModel->selectByList(['uid', 'phone', 'reason', 'create_time'], $page, $limit, $startDate, $endDate, $uid, $phone);

		$count = 0;
		$totalCount = 0;

		if (empty($data)) {
			return [
				'data' => $data,
				'count' => $count,
				'total_count' => $totalCount
			];
		}

		$count = count($data);
		$totalCount = $this->userBlackModel->selectByListCount($startDate, $endDate, $uid, $phone);

		return [
			'data' => $data,
			'count' => $count,
			'total_count' => $totalCount
		];
	}

	public function addUserBlack(array $params)
	{
		$uid = (int)$params['uid'];
		$reason = (string)$params['reason'];

		$userData = $this->userModel->getInfoById($uid, 'phone,is_delete');

		if (empty($userData)) {
			return ['message' => '获取用户想信息失败'];
		}

		$userBlackData = $this->userBlackModel->selectFirstByUid(['uid'], $uid);

		if (!empty($userBlackData)) {
			return ['message' => '当前用户已经是黑名单用户'];
		}

		$phone = $userData['phone'];

		Db::startTrans();
		try {
			$updateUserData = [
				'id' => $uid,
				'is_delete' => 1
			];
			$insertUserBlackData = [
				'uid' => $uid,
				'phone' => $phone,
				'reason' => $reason,
				'create_time' => date('Y-m-d H:i:s')
			];

			$this->userModel->update($updateUserData);
			$this->userBlackModel->insert($insertUserBlackData);
			Db::commit();
			return true;
		} catch (\Exception $e) {
			Db::rollback();
			return ['message' => '系统异常请稍后再试'];
		}
	}

	public function cancelUserBlack(array $params)
	{
		$uid = (int)$params['uid'];

		$userBlackData = $this->userBlackModel->selectFirstByUid(['uid'], $uid);

		if (empty($userBlackData)) {
			return ['message' => '当前用户不是黑名单用户'];
		}

		Db::startTrans();
		try {
			$updateUserData = [
				'id' => $uid,
				'is_delete' => 0
			];

			$this->userModel->update($updateUserData);
			$this->userBlackModel->deleteByUid($uid);
			Db::commit();
			return true;
		} catch (\Exception $e) {
			Db::rollback();
			return ['message' => '系统异常请稍后再试'];
		}
	}
}
